package com.example.my_self_view.calendar

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.my_self_view.databinding.ActivityCalendarBinding
import com.example.my_self_view.util.TimeUtil
import java.util.*

/**
 * @dsc     简介
 * @Author  LiWeiZhong
 * @Date    2025/2/27 10:48
 * @Version 1.0
 */
class CalendarActivity: AppCompatActivity() {

    private lateinit var mBinding: ActivityCalendarBinding
    private val adapter by lazy { CalendarAdapter() }
    private val layoutManager by lazy { LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) }
    private var currentPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityCalendarBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        initData()
    }

    private fun initData() {

        mBinding.dayOfMonth.layoutManager = layoutManager
        mBinding.dayOfMonth.adapter = adapter
        val list = arrayListOf<ItemCalendar>(
            ItemCalendar().apply {
                year = 2024
                month = 12
            },
            ItemCalendar().apply {
                year = 2025
                month = 1
            },
            ItemCalendar().apply {
                year = 2025
                month = 2
            }
        )
        adapter.setData(list)

        PagerSnapHelper().attachToRecyclerView(mBinding.dayOfMonth)
        mBinding.dayOfMonth.overScrollMode = RecyclerView.OVER_SCROLL_ALWAYS
        mBinding.dayOfMonth.setItemViewCacheSize(20);  // 设置缓存视图的个数，视你的需求调整
        mBinding.dayOfMonth.setHasFixedSize(true)

        mBinding.dayOfMonth.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            @SuppressLint("SetTextI18n")
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val firstPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
                val lastPosition = layoutManager.findLastCompletelyVisibleItemPosition()
                if (firstPosition != -1 && firstPosition == lastPosition && currentPosition != firstPosition) {
                    currentPosition = firstPosition
                    adapter.getData(currentPosition).apply {
                        mBinding.yearMonth.text = "$year / $month"
                    }
                }
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()

        for (i in 0 until adapter.itemCount) {
            val calendar = Calendar.getInstance()
            val data = adapter.getData(i)
            calendar.set(Calendar.YEAR, data.year)
            calendar.set(Calendar.MONTH, data.month - 1)
            val date= TimeUtil.TIME_FORMAT("yyyy-MM", calendar.time.time)
            val nowMonth = TimeUtil.TIME_FORMAT("yyyy-MM", Calendar.getInstance().time.time)
            if (date== nowMonth) {
                mBinding.dayOfMonth.scrollToPosition(i)
                mBinding.yearMonth.text = "${data.year} / ${data.month}"
                break
            }
        }


    }

//    @SuppressLint("SetTextI18n")
//    private fun showCalendar() {
//        val calendar = Calendar.getInstance()
//        // 获取年、月
//        val year = calendar.get(Calendar.YEAR)
//        val month = calendar.get(Calendar.MONTH) + 1
//        mBinding.yearMonth.text = "$year / $month"
//
//        // 获取1号是星期几
//        calendar.set(Calendar.DAY_OF_MONTH, 1)
//        val maximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
//        val firstDay = calendar.get(Calendar.DAY_OF_WEEK)
//        val needBlank = if (firstDay == 1) 6 else firstDay - 2
//
//        // 补充前面的
//        for (i in 1..needBlank) {
//            val view = LayoutInflater.from(this).inflate(R.layout.item_day_blank, mBinding.dayOfMonth, false)
//            view.apply {
//                id = View.generateViewId()
//                ids.add(id)
//            }
//            mBinding.dayOfMonth.root.addView(view)
//        }
//
//        for (day in 1..maximum) {
//            val view = LayoutInflater.from(this).inflate(R.layout.item_day, mBinding.dayOfMonth.root, false)
//            view.apply {
//                id = View.generateViewId()
//                ids.add(id)
//
//                // 设置日期
//                val tvNumber = view.findViewById<TextView>(R.id.tv_number)
//                tvNumber.text = day.toString()
//
//                // 设置聚焦监听
//                setOnFocusChangeListener { v, hasFocus ->
//                    val focusNumber = v.findViewById<TextView>(R.id.tv_number)
//                    val focusFestival = v.findViewById<TextView>(R.id.tv_festival)
//                    val focusDate = focusNumber.tag as String
//                    val focusToday = TimeUtil.TIME_FORMAT("yyyy-MM-dd", Calendar.getInstance().time.time)
//                    if (focusDate == focusToday) {
//                        if (hasFocus) {
//                            focusNumber.setTextColor(ContextCompat.getColor(context, R.color.white))
//                            focusFestival.setTextColor(ContextCompat.getColor(context, R.color.white))
//                        } else {
//                            focusNumber.setTextColor(ContextCompat.getColor(context, R.color.blue))
//                            focusFestival.setTextColor(ContextCompat.getColor(context, R.color.grey))
//                        }
//                    } else {
//                        focusNumber.setTextColor(ContextCompat.getColor(context, R.color.black))
//                        focusFestival.setTextColor(ContextCompat.getColor(context, R.color.grey))
//                    }
//                }
//
//                // 是否是今天，若是今天，字体颜色变成蓝色，否则原本颜色
//                calendar.set(Calendar.DAY_OF_MONTH, day)
//                val date= TimeUtil.TIME_FORMAT("yyyy-MM-dd", calendar.time.time)
//                tvNumber.tag = date
//                val today = TimeUtil.TIME_FORMAT("yyyy-MM-dd", Calendar.getInstance().time.time)
//                if (date == today) {
//                    tvNumber.setTextColor(ContextCompat.getColor(context, R.color.selector_focus_blue_white))
//                    background = ContextCompat.getDrawable(context, R.drawable.bg_today)
//                    requestFocus()
//                }
//
//                // 设置农历与节假日
//                val lunar = Solar.fromYmd(year, month, day).lunar
//                val holiday = HolidayUtil.getHoliday(year, month, day)
//                val tvFestival = view.findViewById<TextView>(R.id.tv_festival)
//                if (holiday != null && holiday.day == holiday.target) {
//                    tvFestival.text = holiday.name
//                } else {
//                    val festivals = lunar.festivals
//                    if (festivals.size > 0) tvFestival.text = festivals[0]
//                    else {
//                        if (lunar.dayInChinese == "初一") tvFestival.text = lunar.monthInChinese + "月"
//                        else tvFestival.text = lunar.dayInChinese
//                    }
//                }
//            }
//            mBinding.dayOfMonth.root.addView(view)
//        }
//        mBinding.dayOfMonth.flow.referencedIds = ids.toIntArray()
//    }
}